package com.cn.wanxi.util;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.List;
import java.util.UUID;

public class LoadImg {
    public static void saveImg(HttpServletRequest req) {
        //将图片保存到本地的路径
        String path = "E:\\wanxi\\step-four\\canyin04-1203\\web";
        String outPath = "E:\\wanxi\\step-four\\canyin04-1203\\out\\artifacts\\canyin04_1203_war_exploded";
        String img = "/loadImg/";
//        String path = req.getRealPath(relpath);
        String fn = null;

//        处理缓存数据的一个工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
//        解析数据的方法
        ServletFileUpload sfu = new ServletFileUpload(factory);
        sfu.setHeaderEncoding("UTF-8");  //处理中文问题
        sfu.setSizeMax(1024 * 1024);   //限制文件大小

        try {
            //解码请求 得到所有表单元素
            List<FileItem> fileItems = sfu.parseRequest(req);
            for (FileItem fi : fileItems) {
                //有可能是 文件，也可能是普通文字
                if (fi.isFormField()) { //这个选项是 文字
//                    String name = fi.getName();
                    String fieldName = fi.getFieldName();
                    String value = fi.getString("UTF-8");
                    req.setAttribute(fieldName, value);
                    System.out.println("fieldName：" + fieldName + "表单值为：" + value);
                } else {
                    // 是文件
                    //获取图片后缀名
                    String fileName = fi.getName();

//                    String format = fi.getName().substring(fi.getName().indexOf("."), fi.getName().length());
                    //图片命名
                    UUID uuid = UUID.randomUUID();//得到全球唯一识别码
                    fn = uuid.toString() + "---" + fileName;
                    System.out.println("文件名是：" + fn);  //文件名
                    // fn 是可能是这样的 c:\abc\de\tt\fish.jpg
                    File file = new File(path + img, fn);
                    fi.write(file);

//                    需要将当前的文件复制到out文件里面
                    copy(file, outPath + img, fn);
                    req.setAttribute("imgHref", img + fn);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 边读边写
     * @param file
     * @param path
     * @param fileName
     */
    private static void copy(File file, String path, String fileName) {
        try {
            InputStream inputStream = new FileInputStream(file);
            File outFile = createFile(path, fileName);
            OutputStream outputStream = new FileOutputStream(outFile);
            int leng = 0;
            while ((leng = inputStream.read()) != -1) {
                outputStream.write(leng);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 创建文件夹和文件
     * @param path
     * @param fileName
     * @return
     */
    private static File createFile(String path, String fileName) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        File file1 = new File(file, fileName);
        try {
            file1.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file1;
    }
}
